const  express = require('express');
const router = express.Router();
const { success, failure } = require('../utils/response');
const {Article} = require("../models")

// 获取文章列表接口
router.get("/",async(req,res)=>{
    try {
        const query = req.query;
        
        const pageIndex = Math.abs(query.pageIndex) || 1;
        const pageSize = Math.abs(query.pageSize) || 10;
        const offset = (pageIndex - 1) * pageSize;

        const condition = {
            attributes:{exclude:["content"]},
            order:[["id","DESC"]],
            limit:pageSize,
            offset:offset
        }

        const {count,rows} = await Article.findAndCountAll(condition)

        const result = {
            pagination:{
                total:count,
                pageIndex,
                pageSize
            },
            data:rows
        }
        success(res,"获取文章列表成功",result)
    } catch (error) {
        failure(res,error)
    }
})

// 查询文章详情
router.get("/:id",async(req,res)=>{
    try {
        const {id} = req.params

        const article = await Article.findByPk(id)
        if(!article){
            return failure(res,"文章不存在",404)
        }
        success(res,"获取文章详情成功",{article})
    } catch (error) {
        failure(res,error)
    }
})

module.exports = router;